﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using EventMgrLib;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;
using SmartMotion.Core;
using SmartMotion.Core.Mgrs;
using Sunny.UI;
using WeifenLuo.WinFormsUI.Docking;
using FileSystem = Microsoft.VisualBasic.FileIO.FileSystem;
using UIOption = Microsoft.VisualBasic.FileIO.UIOption;

namespace SmartMotion.Pages.DockPages
{
    public partial class FrmSolutionMgr : DockContent
    {
        #region 字段

        private TreeNode _clickNode;
        private FlowsMgr _flowsMgr;
        private EventMgr _em;
        private List<Flow> _searchFlows;

        #endregion

        #region 窗体创建加载关闭

        public FrmSolutionMgr()
        {
            InitializeComponent();
        }

        private void FrmSolutionMgr_Load(object sender, EventArgs e)
        {
            HideOnClose = true;
            _flowsMgr=FlowsMgr.Ins;
            _em=EventMgr.Ins;
            _em.GetEvent<FlowEvent>().Subscribe(FileOperate);
            _searchFlows = new List<Flow>();
            ShowFlowsToTreeView();
        }

        private void FrmSolutionMgr_FormClosing(object sender, FormClosingEventArgs e)
        {
            _em.GetEvent<FlowEvent>().Unsubscribe(FileOperate);
        }
        

        #endregion

        #region 右键菜单

        private void 创建流程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region 获得分组名称

            string groupName = string.Empty;
            if (_clickNode!=null)
            {
                groupName = _clickNode.Nodes.Count > 0 ? _clickNode.Text : _clickNode.Parent.Text;
            }
            else
            {
                if (!UIInputDialog.InputStringDialog(ref groupName,true,"请输入分组名称")) return;
             
            }

            #endregion

            string newFlowName=String.Empty;
            retry:
            if (UIInputDialog.InputStringDialog(ref newFlowName,true,"请输入流程名称"))
            {
                if (_flowsMgr.Flows.Any(flow=>flow.Name==newFlowName))
                {
                    UIMessageBox.ShowError($"{newFlowName } 已存在，请重新输入");
                    goto  retry;
                }
                else
                {
                    var newFlow = new Flow
                    {
                        Group = groupName,
                        Name = newFlowName
                    };
                    _flowsMgr.Flows.Add(newFlow);
                    ShowFlowsToTreeView();

                    _em.GetEvent<ShowEditFrm>().Publish(newFlow);
                }
            }


        }

        private void 删除流程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_clickNode==null) return;

            if (UIMessageBox.ShowAsk($"是否将流程[{_clickNode.Text}]放入回收站?"))
            {
                string filePath = $"{_flowsMgr.Path}{_clickNode.Text}.xml";
                if (File.Exists(filePath))
                {
                    FileSystem.DeleteFile(filePath,
                        UIOption.OnlyErrorDialogs,
                        RecycleOption.SendToRecycleBin);
                    Flow delFlow = _flowsMgr.Flows.Find(flow => flow.Name == _clickNode.Text);
                    _flowsMgr.Flows.Remove(delFlow);
                    ShowFlowsToTreeView();
                    _em.GetEvent<DellFlow>().Publish(delFlow.Name);
                }
            }

        }

        private void 重命名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lblRetry:
            string newFlowName = "";
            if (UIInputDialog.InputStringDialog(ref newFlowName,true,"请输入新流程名称"))
            {
                if (_flowsMgr.Flows.Any(f=>f.Name==newFlowName))
                {
                    UIMessageBox.ShowError("新流程名称重复，请重新输入一个流程名字");
                    goto lblRetry;
                }

                var flow = _flowsMgr.GetFlow(_clickNode.Text);
                string filePath = $"{_flowsMgr.Path}{flow.Name}.xml";
                string newFilePath = $"{_flowsMgr.Path}{newFlowName}.xml";
                File.Move(filePath,newFilePath);
                _clickNode.Text = newFlowName;
                flow.Name = newFlowName;
                _em.GetEvent<RenameFlow>().Publish(flow);

            }
        }
        

        #endregion

        private void FrmSolutionMgr_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Delete)
            {
                删除流程ToolStripMenuItem_Click(null, null);
            }

            if (e.KeyCode==Keys.F2)
            {
                重命名ToolStripMenuItem_Click(null, null);
            }
        }

        private void FileOperate(FileOpt opt)
        {
            switch (opt)
            {
                case FileOpt.None:
                    break;
                case FileOpt.Create:
                    break;
                case FileOpt.Open:
                    break;
                case FileOpt.Save:
                    _flowsMgr.SaveFlows();
                    break;
                case FileOpt.SaveAs:
                    break;
                case FileOpt.Add:
                    break;
                case FileOpt.Del:
                    break;
                case FileOpt.Edit:  
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(opt), opt, null);
            }
        }

        private void ShowFlowsToTreeView()
        {
            tv.Nodes.Clear();
            var groups = _flowsMgr.Flows.Select(flow => flow.Group).ToList().Distinct().ToList();
            foreach (var gpName in groups)
            {
                var gpNode = new TreeNode()
                {
                    Text = string.IsNullOrEmpty(gpName) ? "Default" : gpName,
                    ImageIndex = 0,
                    SelectedImageIndex = 0,
                };
                foreach (var flow in _flowsMgr.Flows)
                {
                    if (flow.Group!=gpName) continue;

                    var flowNode = new TreeNode(flow.Name)
                    {
                        ImageIndex = 1,
                        SelectedImageIndex = 1,
                    };
                    gpNode.Nodes.Add(flowNode);//把子节点添加到分组节点
                }

                tv.Nodes.Add(gpNode);//把分组节点添加到树
            }
            tv.ExpandAll();
        }

        private void tv_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Left:
                    if (e.Node==null) return;
                    var findFlow = _flowsMgr.Flows.Find(flow => flow.Name == e.Node.Text);
                    _em.GetEvent<SelectedObjectChanged>().Publish(findFlow);
                    _clickNode = tv.GetNodeAt(e.X, e.Y);
                    break;
                case MouseButtons.None:
                    break;
                case MouseButtons.Right:
                    _clickNode = tv.GetNodeAt(e.X, e.Y);
                    break;
                case MouseButtons.Middle:
                    break;
                case MouseButtons.XButton1:
                    break;
                case MouseButtons.XButton2:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private void tv_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            var findFlow = _flowsMgr.Flows.Find(flow => flow.Name == e.Node.Text);
            if (findFlow!=null)
            {
                _em.GetEvent<ShowEditFrm>().Publish(findFlow);
            }
        }

        private void FrmSolutionMgr_Resize(object sender, EventArgs e)
        {
            txtSearchTool.Height = 30;
        }

        private void txtSearchTool_TextChanged(object sender, EventArgs e)
        {
            string txtSearch = txtSearchTool.Text;
            _searchFlows.Clear();
            foreach (var flow in _flowsMgr.Flows)
            {
                if (flow.Name.ToLower().Contains(txtSearch.ToLower()))
                {
                    _searchFlows.Add(flow);
                }
            }

            tv.Nodes.Clear();

            var groups = _searchFlows.Select(flow => flow.Group).ToList().Distinct().ToList();
            foreach (var gpName in groups)
            {
                var gpNode = new TreeNode()
                {
                    Text = string.IsNullOrEmpty(gpName) ? "Default" : gpName,
                    ImageIndex = 0,
                    SelectedImageIndex = 0,
                };
                foreach (var flow in _searchFlows)
                {
                    if (flow.Group != gpName) continue;

                    var flowNode = new TreeNode(flow.Name)
                    {
                        ImageIndex = 1,
                        SelectedImageIndex = 1,
                    };
                    gpNode.Nodes.Add(flowNode);//把子节点添加到分组节点
                }

                tv.Nodes.Add(gpNode);//把分组节点添加到树
            }
            tv.ExpandAll();
        }
    }
}
